package org.hales.security;

import org.hales.common.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hales.common.Enum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class UrlAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

       // httpServletResponse.setStatus(400);
        Object obj = ServerResponse.createByErrorCodeMessage(Enum.ResponseCode.NEED_LOGIN.getCode(), Enum.ResponseCode.NEED_LOGIN.getDesc());
        ObjectMapper objMapper = new ObjectMapper();
        String result = objMapper.writeValueAsString(obj);
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(result);
        writer.close();
        httpServletResponse.flushBuffer();

    }
}